﻿
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using DataCapture.DeviceDataSave;
using DataCollectionSystem.Helper;



namespace DataCapture.Helper;
/// <summary>
/// 设备数据处理
/// </summary>
public class DeviceDataProcessingHelper
{



    private static ConcurrentDictionary<string, DeviceBase> Dic_deviceDataCapture = new ConcurrentDictionary<string, DeviceBase>();
    private PublicHelp.AppSettings plAppSettings;

    public DeviceDataProcessingHelper(CancellationToken cancellationToken)
    {
        plAppSettings = ConfigurationHelper.GetAppSettings;

        //必须等待PLC连接后在开启设备数据读取
        ReadDeviceRealDataAsync(cancellationToken);

    }

    /// <summary>
    /// 开启设备数据读取
    /// </summary>
    /// <param name="cancellationToken"></param>
    private void ReadDeviceRealDataAsync(CancellationToken cancellationToken)
    {

        for (int i = 0; i < plAppSettings.PlcServer.Count; i++)
        {
            var plcServerConfig = plAppSettings.PlcServer[i];
            if (plcServerConfig.Enabled)
            {//plc启用
                for (int j = 0; j < plcServerConfig.ElementConfig.Count; j++)
                {
                    var elementConfig = plcServerConfig.ElementConfig[j];
                    if (elementConfig.Enabled)
                    {//设备启用
                        if (!Dic_deviceDataCapture.ContainsKey(elementConfig.DeviceId))
                        {
                            DeviceBase captureBase = null;

                            if (plcServerConfig.PlcName == Define.plc_RXJ)
                            {
                                captureBase = new DeviceRXJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//绕线机
                                AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                            }
                            else if (plcServerConfig.PlcName == Define.plc_LMXC)
                            {
                                if (elementConfig.DataType == "LMTSJ")
                                {
                                    captureBase = new DeviceLMTSJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//龙门提升
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                                else if (elementConfig.DataType == "ZJFFJ")
                                {
                                    captureBase = new DeviceZJFFJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//载具分发机
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                            }
                            else if (plcServerConfig.PlcName == Define.plc_XTCLJ_A || plcServerConfig.PlcName == Define.plc_XTCLJ_B)
                            {
                                captureBase = new DeviceXTCLJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//线材处理
                                AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                            }
                            else if (plcServerConfig.PlcName == Define.plc_ZSCQ_A || plcServerConfig.PlcName == Define.plc_ZSCQ_B)
                            {
                                if (elementConfig.DataType == "JSZSJ")
                                {
                                    captureBase = new DeviceJSZSJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//胶塞注塑机数据
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                                else if (elementConfig.DataType == "XXBPJCJ")
                                {
                                    captureBase = new DeviceXXBPJCJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//芯线剥皮检测机数据
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                            }
                            else if (plcServerConfig.PlcName == Define.plc_MAOJIE_A || plcServerConfig.PlcName == Define.plc_MAOJIE_B)
                            {
                                if (elementConfig.DataType == "XPMJJ")
                                {
                                    captureBase = new DeviceXPMJJ(plcServerConfig.PlcName, elementConfig, cancellationToken);
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                                else if (elementConfig.DataType == "JGJC")
                                {
                                    captureBase = new DeviceJGJC(plcServerConfig.PlcName, elementConfig, cancellationToken);//激光检测
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                            }
                            else if (plcServerConfig.PlcName == Define.plc_SANMA_A || plcServerConfig.PlcName == Define.plc_SANMA_B)
                            {
                                if (elementConfig.DataType == "KKJ")
                                {
                                    captureBase = new DeviceKKJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//卡口机
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                                else if (elementConfig.DataType == "ZDTBJ")
                                {
                                    captureBase = new DeviceZDTBJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//不良品替补
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                                else if (elementConfig.DataType == "JGDMZSGJ")
                                {
                                    captureBase = new JGDMZSGJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//激光打码装上盖数据
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);

                                }
                            }
                            else if (plcServerConfig.PlcName == Define.plc_JCGJ)
                            {
                                captureBase = new DeviceJCGSLJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//基础管上料
                                AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);

                            }
                            else if (plcServerConfig.PlcName == Define.plc_ZHEXIAN_A || plcServerConfig.PlcName == Define.plc_ZHEXIAN_B)
                            {
                                if (elementConfig.DataType == "ZDZDJ")
                                {
                                    captureBase = new DeviceZDZDJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//自动装袋机
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                                else if (elementConfig.DataType == "ZXTBJ")
                                {
                                    captureBase = new DeviceZXTBJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//装箱贴标机
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);

                                }
                                else if (elementConfig.DataType == "JXS")
                                {
                                    captureBase = new DeviceJXS(plcServerConfig.PlcName, elementConfig, cancellationToken);//机械手
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);

                                }

                            }
                            else if (plcServerConfig.PlcName == Define.plc_ZPJ)
                            {
                                if (elementConfig.DataType == "JXSZPJ")
                                {
                                    captureBase = new DeviceJXSZPJ(plcServerConfig.PlcName, elementConfig, cancellationToken);//组批间机械手
                                    AddDeviceData(plcServerConfig.PlcName, elementConfig.DeviceId, captureBase);
                                }
                            }

                        }
                    }
                    else
                    {
                        Log4NetHelper.Debug($"当前有设备配置，尚未启用 {elementConfig.DeviceId}", true);
                    }
                }
            }
           
        }
    }
    /// <summary>
    /// 设备数据处理
    /// </summary>
    /// <param name="plcName"></param>
    /// <param name="deviceId"></param>
    /// <param name="captureBase"></param>
    private void AddDeviceData(string plcName, string deviceId, DeviceBase captureBase)
    {
        if (captureBase != null)
        {
            Dic_deviceDataCapture.TryAdd(deviceId, captureBase);
        }
        else
        {
            Log4NetHelper.Error($"PLC类型{plcName}  设备{deviceId}未定义", true);
        }
    }
    /// <summary>
    /// 解码告警数据
    /// </summary>
    public static bool[] TestDecode(ushort data)
    {

        //ushort data = 0x1234; // 示例数据，二进制：0001001000110100

        // 创建布尔数组存储每一位的状态（true为1，false为0）
        bool[] alarmFlags = new bool[16];

        // 遍历每一位
        for (int i = 0; i < 16; i++)
        {
            //alarmFlags[i] = new Random().Next(0, 2) == 1;
            alarmFlags[i] = true;
        }
        return alarmFlags;

    }
    /// <summary>
    /// 解码告警数据
    /// </summary>
    public static bool[] Decode(ushort data)
    {

        //ushort data = 0x1234; // 示例数据，二进制：0001001000110100

        // 创建布尔数组存储每一位的状态（true为1，false为0）
        bool[] alarmFlags = new bool[16];

        // 遍历每一位
        for (int i = 0; i < 16; i++)
        {
            // 创建掩码：1 << i（例如i=0时掩码是0b1，i=1时是0b10，依此类推）
            int mask = 1 << i;

            // 按位与操作，判断该位是否为1
            bool isSet = (data & (mask)) != 0;

            // 存储结果到数组
            alarmFlags[i] = isSet;

            // 输出结果（可选）
            // Console.WriteLine($"Bit {i}: {isSet}");
        }
        return alarmFlags;

    }
    /// <summary>
    /// 将超过10的位索引转换为字母标签（a~f对应11~15位）
    /// </summary>
    public static char GetLetterLabel(int index)
    {
        if (index < 0 || index > 15)
        {
            throw new ArgumentOutOfRangeException(nameof(index), "索引必须在0到15之间");
        }
        if (index < 10)
        {
            return (char)('0' + index);
        }
        else
        {
            return (char)('a' + (index - 10));
        }
    }
}